package com.itserver.service.sys.impl;

import com.itserver.mapper.sys.MenuMapper;
import com.itserver.mapper.sys.RoleMapper;
import com.itserver.mapper.sys.UserMapper;
import com.itserver.pojo.PageResult;
import com.itserver.pojo.sys.Menu;
import com.itserver.pojo.sys.Role;
import com.itserver.pojo.sys.User;
import com.itserver.service.sys.MenuService;
import com.itserver.utils.JwtUtils;
import com.itserver.utils.RequestHeader;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashSet;
import java.util.List;

import static java.util.Arrays.stream;

@Service

public class MenuServiceImpl  implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult<Menu> list(Menu params) {
        List<Menu> menus = menuMapper.list(params);
        return new PageResult<>((long) menus.size(), menus);
    }

    @Override
    public void delete(List<Integer> ids) {
        menuMapper.delete(ids);
    }

    @Override
    public void add(Menu menu) {
        menuMapper.add(menu);
    }

    @Override
    public void update(Menu menu) {
        menuMapper.update(menu);
    }

    @Override
    public Menu getById(Integer id) {
        return menuMapper.getById(id);
    }

    @Override
    public PageResult<Menu> getUserMenus() {
        Integer id = RequestHeader.getUserId();
        User user = userMapper.getById(id);
        String roles =  user.getRoles();
        if( roles!=null && !roles.isEmpty()){
            List<Integer> roleIds = stream(roles.split(",")).map(Integer::parseInt).toList();
            List<Role> rolesList = roleMapper.getByIdsMenu(roleIds);
            HashSet<Integer> menus = new HashSet<>();
            rolesList.forEach(role -> {
                if(role!=null && role.getMenuIds()!=null && !role.getMenuIds().isEmpty()){
                    List<Integer> menuIds = stream(role.getMenuIds().split(",")).map(Integer::parseInt).toList();
                    menus.addAll(menuIds);
                }
            });
            List<Menu> menuList  = menuMapper.getByIds(menus);

            return  new PageResult<>((long) menuList.size(), menuList);
        }
        return null;
    }
}
